package com.zhisuo.apicenter.util;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class HttpclientUtils {
	
	private static final Logger logger = LogManager.getLogger("HttpclientUtils");

	public static CloseableHttpClient newHttpClients() {
		return HttpClients.custom()
		.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000).build())
		.setSSLHostnameVerifier(new NoopHostnameVerifier())
		.build();
	}
	
	public static String post(String url, ContentType contentType, String content) {
		HttpPost req = new HttpPost(url);
		req.setEntity(new StringEntity(content, contentType));
		
		try (CloseableHttpClient client = newHttpClients();
			 CloseableHttpResponse resp = client.execute(req)){
			return EntityUtils.toString(resp.getEntity(), "UTF-8");
		} catch (Exception e) {
			logger.warn("post execute error!",e);
		}
		
		return null;
	}
	
	public static String postJson(String url, String content) {
		return post(url, ContentType.APPLICATION_JSON, content);
	}
}
